
from tornado.web import RequestHandler
from pycket.session import SessionMixin
from utils import auth


class AuthBaseHandler(RequestHandler, SessionMixin):
    def get_current_user(self):
        return self.session.get("user_id")


class LoginHandler(AuthBaseHandler):
    def get(self):
        next_url = self.get_argument("next", "/")
        self.render("login.html", next_url=next_url)

    def post(self):
        username = self.get_argument("username", "")
        password = self.get_argument("password", "")
        next_url = self.get_argument("next", "/")
        if auth.authenticate(username, password):
            self.session.set("user_id", username)
            self.redirect(next_url)

        else:
            self.write("login error")


class LogoutHandler(AuthBaseHandler):
    def get(self):
        self.session.set("user_id", "")
        self.redirect("/login")


class SignupHandler(AuthBaseHandler):
    def get(self):
        self.render("signup.html")

    def post(self):
        username = self.get_argument("username", "")
        password1 = self.get_argument("password1", "")
        password2 = self.get_argument("password2", "")
        if password1 == password2:
            ret = auth.register(username, password1)
            if ret["msg"] == "ok":
                self.session.set("user_id", username)
                self.redirect("/login")
            else:
                self.write("该用户已注册")

        else:
            self.write("register wrong")



